<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>demo</title>
</head>
<body>
<h3>选择一张图片并通过websocket发送到后台</h3>
<input accept="image/*" type="file" id="file">
<br/>
<h3>后台会实时通过websocket把图片回传（可以把本页面打开两个以测试效果）</h3>
<div style="width: 800px; height: 600px;">
<img alt="" id="img" width="800" height="600" src=""/>
</div>
</body>
<script type="text/javascript" src="js/jquery-2.1.4.min.js"></script>
<script type="text/javascript" src="js/stomp.js"></script>
<script type="text/javascript" src="js/websocket.js"></script>
<script type="text/javascript">

	// ！！！！不是原生的WebSoceket，使用的spring-boot-starter-websocket包，基于STOMP协议的WebSocket
	
	//websocket链接成功后回调
	function init(websocket){
		$("#file").change(function(){
			var objectURL=URL.createObjectURL($(this)[0].files[0]);
			console.log(objectURL);
			var reader = new FileReader();
	        reader.onloadend=function() {
	        	if(reader.result.byteLength>0){
		            //reader.result是一个含有视频数据流的Blob对象
		            var buf = new Uint8Array(reader.result);
		            //如果发送字节消息，第三个参数设置true
		            websocket.send("/topic/server/byte",buf,true);
		            console.log(">>> 已发送");
	        	}
	        };
	        reader.readAsArrayBuffer($(this)[0].files[0]);
		});
		
		//订阅一个topic
		websocket.subscribe("/topic/node",function(msg){
			console.log(msg);
			//字节消息
			if(msg.isByte){
 			  	var blob = new Blob([msg.body], { type: "image/jpg" });
 			  	var objectURL = URL.createObjectURL(blob);
 			  	$("#img").prop("src",objectURL);
 			  	setTimeout(function(){
 			  		URL.revokeObjectURL(objectURL);
 	 			  	msg.body=null;
 			  	},1000);
			}
		});	
	}

</script>

</html>